from rest_framework.views import APIView
from rest_framework.response import Response
from alipay import AliPay
from django.conf import settings
import os
from orders.models import OrderInfo
from .models import Payment

class AlipayURLView(APIView):
    def get(self,request,order_id):
        #创建slipay对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(settings.BASE_DIR,
    'apps/payments/keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(settings.BASE_DIR,
    'apps/payments/keys/alipay_public_key.pem'),
            debug=settings.ALIPAY_DEBUG
        )
        #查询订单对象
        try:
            order = OrderInfo.objects.get(pk=order_id)
        except:
            return Response({'message':"无效的订单编号"})

        #调用方法，生成支付地址
        order_string=alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,#订单编号
            total_amount=str(order.total_amount),#支付总金额
            subject='美多商城-订单支付',
            return_url=settings.ALIPAY_RETURN_URL
        )
        alipay_url = settings.ALIPAY_URL + order_string

        return Response({'alipay_url':alipay_url})


class AliPaySaveView(APIView):
    def put(self,request):
        #验证是否支付成功
        data = request.query_param.dict()
        #sig不能参与签名验证
        signature = data.pop("sign")

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(settings.BASE_DIR,
                                              'apps/payments/keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(settings.BASE_DIR,
                                                'apps/payments/keys/alipay_public_key.pem'),
            debug=settings.ALIPAY_DEBUG
        )

        success = alipay.verify(data,signature)
        if success:
            # print("trade_succeed")
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id = order_id,
                trade_id = trade_id
            )
            #修改订单状态
            OrderInfo.objects.filter(pk=order_id).update(status=2)
            #响应
            return Response({"trade_id":trade_id})
        else:
            return Response({"message":"支付失败"})

